package com.naiterui.ehp.bs.search.service.impl.core;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.search.exception.ExceptionCodes;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author guoyongxiang
 * @date 2019-08-27 15:20
 * @since 1.0.0
 */
@Service
public class EsIndexService {

    private static final Logger LOGGER = LoggerFactory.getLogger(EsIndexService.class);

    /**
     * 搜索服务注入
     */
    @Autowired
    private RestHighLevelClient esClient;

    public void update(UpdateRequest updateRequest) throws BusinessException {
        try {
            esClient.update(updateRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            LOGGER.error("修改文档异常 updateRequest:{}", updateRequest, e);
            throw new BusinessException(ExceptionCodes.INDEX_OPERATION_FAILED);
        }
    }

    /**
     * 根据条件批量删除,由于2.x版本删除批量删除方法(1.x批量删除会导致强制刷新可能引起内存溢出)故先查询ID再删除
     * BaseIndexService.bulkDelete()
     *
     * @param indexName
     * @param type
     * @param queryBuilder
     * @param size
     * @Author guoyongxiang
     * @Date 2016年8月6日
     * @since 1.0.0
     */
    public void bulkDelete(String indexName, QueryBuilder queryBuilder, int size) throws BusinessException {
        SearchRequest searchRequest = new SearchRequest(indexName);
        searchRequest.searchType(SearchType.DFS_QUERY_THEN_FETCH);
        SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.searchSource().query(queryBuilder);
        searchSourceBuilder.size(size);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
            BulkRequest bulkRequest = new BulkRequest();
            for (SearchHit hit : response.getHits()) {
                String id = hit.getId();
                bulkRequest.add(new DeleteRequest(indexName, id));
            }

            if (response.getHits().getTotalHits().value > 0) {
                BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                if (bulkResponse.hasFailures()) {
                    Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getFailureMessage).forEachOrdered(LOGGER::info);
                } else {
                    LOGGER.info("delete ok: {}", queryBuilder.toString());
                }
            }
        } catch (IOException e) {
            LOGGER.error("批量删除操作失败 indexName:{}", indexName, e);
            throw new BusinessException(ExceptionCodes.INDEX_OPERATION_FAILED);
        }
    }

    /**
     * 批量操作文档
     *
     * @param indexName
     * @param type
     * @param bulkRequest
     * @return
     * @throws BusinessException
     */
    public BulkResponse bulkOperation(String indexName, BulkRequest bulkRequest) throws BusinessException {
        try {
            BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                Arrays.stream(bulkResponse.getItems()).map(BulkItemResponse::getFailureMessage).forEachOrdered(LOGGER::info);
            } else {
                LOGGER.info("operation ok: {}, ", bulkRequest.getDescription());
            }
            return bulkResponse;
        } catch (IOException e) {
            LOGGER.error("批量操作文档失败 indexName:{}, bulkRequest:{}", indexName, bulkRequest, e);
            throw new BusinessException(ExceptionCodes.INDEX_OPERATION_FAILED);
        }
    }
}
